package avgCitySalary;

import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;

public class AvgSalaryMapper extends Mapper<LongWritable, Text, Text, DoubleWritable> {
    private final Text outKey = new Text();
    private final DoubleWritable outValue = new DoubleWritable();

    private int flag = 1 ;
    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        if(flag == 1){
            flag ++ ;
            return;
        }
        String line = value.toString();
        String[] fields = line.split(",");
        if (fields.length > 7) {
            String salary = fields[6].trim(); // 薪资字段
            String city = fields[7].trim(); // 城市字段
            double[] salaries = parseSalary(salary);
            outKey.set(city);
            outValue.set((salaries[0] + salaries[1]) / 2); // 计算平均薪资
            context.write(outKey, outValue);
        }
    }

    private double[] parseSalary(String salary) {
        String[] parts = salary.split("-");
        double leftSalary = Double.parseDouble(parts[0].trim());
        double rightSalary = Double.parseDouble(parts[1].trim().replace("万",""));
        return new double[]{leftSalary, rightSalary};
    }
}